package cn.edu.zafu.bigdata.x.zcy_0217;

import java.io.*;
import java.net.*;

public class TimeServer {
    public static void main(String[] args) {
        int port = 1234; // 服务端端口号
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("Time server is running and waiting for client requests...");

            byte[] receiveBuffer = new byte[1024];
            byte[] sendBuffer = new byte[1024];

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                socket.receive(receivePacket);
                String request = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Received time request from " + receivePacket.getAddress().getHostAddress());

                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                long currentTime = System.currentTimeMillis();

                sendBuffer = Long.toString(currentTime).getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);
                socket.send(sendPacket);
                System.out.println("Sent time " + currentTime + " to client");
            }
        } catch (SocketException e) {
            System.err.println("Socket exception: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
